#include "uart.h"

uart::uart(QObject *parent) :
    QObject(parent)
{
}

int uart::uartScan(int *fd)
{
    int ret;
    int x_ret;
    for(x_ret=0;x_ret<100;x_ret++)
    {
        QString dev = "/dev/ttyAMA"+QString::number(x_ret);
        char *c_dev = dev.toLatin1().data();
        *fd = open(c_dev, O_RDWR | O_NOCTTY);
        if (*fd == -1)
        {
            printf("openPort: Unable to open port %s\n", SERIAL_DEV_0);
            continue;
        }
        else
        {
            ret = 0;
            break;
        }
    }

    return ret;
}
int uart::uartInit()
{
    int fd = -1;
    /* Port options */
    struct termios options;
    /* Open port for read and write not making it a controlling terminal */
    if ((uartScan(&fd)) == -1)
    {
        printf("Init the uart fail!\n");
        return -1;
    }
    tcgetattr(fd, &options);
    memset(&options, 0, sizeof(options));

    cfsetispeed(&options, BAUD_RATE);
    cfsetospeed(&options, BAUD_RATE);

    options.c_iflag = 0;
    options.c_oflag = 0;
    options.c_cflag |= (CLOCAL | CREAD | CS8);
    options.c_cflag &= ~PARENB; /* Parity disabled */
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_lflag=0;

    cfmakeraw(&options);

    options.c_cc[VMIN] = RD_NUM;
    options.c_cc[VTIME] = 10;

    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &options);

    /*
         * Sleep for UART to power up and set options
         * Note: pls don't change the usleep.
         */
    usleep(1000);
    printf("UART->DLP: init done \n");
    return fd;
}
